package com.example.rustfs.service;

import com.example.rustfs.dao.UserDao;
import com.example.rustfs.dto.RegisterRequest;
import com.example.rustfs.dto.UserInfo;
import com.example.rustfs.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;

/**
 * 用户服务类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {
    
    private final UserDao userDao;
    
    /**
     * 用户登录
     */
    public User login(String username, String password) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 实际应该使用加密后的密码比对
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 更新最后登录时间
        userDao.updateLastLoginTime(user.getId());
        
        log.info("用户登录成功: {}", username);
        return user;
    }
    
    /**
     * 用户注册
     */
    public User register(RegisterRequest request) {
        // 验证用户名是否已存在
        if (userDao.existsByUsername(request.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 验证密码是否一致
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }
        
        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword()); // 实际应该加密
        user.setEmail(request.getEmail());
        user.setNickname(request.getNickname());
        user.setStorageUsed(0L);
        user.setStorageLimit(10737418240L); // 默认10GB
        user.setCreateTime(LocalDateTime.now());
        user.setLastLoginTime(LocalDateTime.now());
        
        userDao.save(user);
        log.info("用户注册成功: {}", user.getUsername());
        return user;
    }
    
    /**
     * 获取用户信息
     */
    public UserInfo getUserInfo(Long userId) {
        User user = userDao.findById(userId);
        if (user == null) {
            return null;
        }
        
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setEmail(user.getEmail());
        userInfo.setNickname(user.getNickname());
        userInfo.setStorageUsed(user.getStorageUsed());
        userInfo.setStorageLimit(user.getStorageLimit());
        userInfo.setStorageUsedFormatted(formatFileSize(user.getStorageUsed()));
        userInfo.setStorageLimitFormatted(formatFileSize(user.getStorageLimit()));
        
        // 计算使用百分比
        if (user.getStorageLimit() > 0) {
            userInfo.setStorageUsagePercent(
                (int) ((user.getStorageUsed() * 100) / user.getStorageLimit())
            );
        } else {
            userInfo.setStorageUsagePercent(0);
        }
        
        return userInfo;
    }
    
    /**
     * 更新存储空间使用量
     */
    public void updateStorageUsed(Long userId, Long storageUsed) {
        userDao.updateStorageUsed(userId, storageUsed);
    }
    
    /**
     * 格式化文件大小
     */
    private String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

